package twentytwentyone_3;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @Author: Zahi
 * @Description:
 * @Date Created in 2021-03-25 8:57
 * @Modified By:
 */
public class LongestWord_720 {
    public static void main(String[] args){
        String[] words = new String[]{"w","wo","wor","worl","world"};
        System.out.println(longestWord(words));
    }

    public static String longestWord(String[] words){
        String result = "";
        Set<String> sets = new HashSet<>(Arrays.asList(words));
        for (String word : words) {
            int worldLength = word.length();
            int resultLength = result.length();
            if (worldLength > resultLength || worldLength == resultLength && word.compareTo(result) < 0){
                boolean flag = true;
                for (int i = 1; i < word.length(); i++) {
                    if (!sets.contains(word.substring(0,i))){
                        flag = false;
                        break;
                    }
                }
                if (flag){
                    result = word;
                }
            }
        }
        return result;
    }
}
